package com.luli.test;

import java.lang.management.ManagementFactory;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import com.sun.management.OperatingSystemMXBean;

public class CPUMonitor {

    private OperatingSystemMXBean osBean;

    public CPUMonitor() {
        this.osBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    }

    public double getSystemCpuLoad() {
        return osBean.getSystemCpuLoad();
    }

    public static void main(String[] args) throws Exception {
        CPUMonitor monitor = new CPUMonitor();
        while (true) {
            double cpuLoad = monitor.getSystemCpuLoad();
            System.out.printf("当前CPU使用率: %.2f%%\n", cpuLoad * 100);
            Thread.sleep(5000); // 每5秒采集一次数据
        }
    }
}

